require 'json'

EMCC_FLAGS = ENV["EMCC_FLAGS"] || "-O3 -D_ERROR_PRINT -s ALLOW_MEMORY_GROWTH=1 -s WASM=1"

EMCC_FLAGS = "-O0 -g4 -D_ASSERT_USED -D_ERROR_PRINT -s ALLOW_MEMORY_GROWTH=1 -s WASM=1" if ENV["DEBUG"]

c_files = FileList["../src/*.c"]

exported_functions = [
	"_malloc",
	"_free",
	"_memcpy",
	"_h264bsdAlloc",
	"_h264bsdFree",
	"_h264bsdInit",
	"_h264bsdDecode",
	"_h264bsdShutdown",
	"_h264bsdNextOutputPicture",
	"_h264bsdNextOutputPictureRGBA",
	"_h264bsdPicWidth",
	"_h264bsdPicHeight",
	"_h264bsdCroppingParams",
]

exported_runtime_methods = [
	'getValue',
	'setValue'
]

EXPORT_FLAGS = "-s EXTRA_EXPORTED_RUNTIME_METHODS='#{JSON.generate(exported_runtime_methods)}' -s EXPORTED_FUNCTIONS='#{JSON.generate(exported_functions)}'"

file "h264bsd_wasm.js" => c_files do
	sh "emcc #{c_files.join(' ')} #{EMCC_FLAGS} #{EXPORT_FLAGS} -o h264bsd_wasm.js"
end

task :clean do
	FileUtils.rm_f("h264bsd_wasm.js")
	FileUtils.rm_f("h264bsd_wasm.wasm")
end

desc "Check for prereq tools"
task :setup do
	sh("emcc --version") { |ok, res| fail("Can't find emscripten binaries.") unless ok }
	puts("Ready to go")
end

task :server do
	require 'webrick'
	WEBrick::HTTPServer.new(:Port => 8000, :DocumentRoot => Dir.pwd).start
end

task :build => [:setup, 'h264bsd_wasm.js']

task :test do
	sh "node test_node.js"
end

task :default => [:build]
